package com.pdg.islandinterloper.database.tableproviders;

import java.util.Iterator;
import java.util.List;
import java.util.Random;

import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;

import com.pdg.islandinterloper.MainActivity;
import com.pdg.islandinterloper.database.IslandInterloperDatabase;
import com.pdg.islandinterloper.database.baseclasses.TableProviderBase;
import com.pdg.islandinterloper.database.objects.Profile;
import com.pdg.islandinterloper.database.objects.WorldPosition;

public class IslandTableProvider extends
		TableProviderBase<MainActivity, IslandInterloperDatabase> {
	private static final String TABLE_NAME = "islands";
	private static final String FIELD_ID="_id";
	private static final String FIELD_ISLAND_NAME="island_name";
	private static final String FIELD_ISLAND_X="island_x";
	private static final String FIELD_ISLAND_Y="island_y";
	private static final String FIELD_PROFILE_ID="profile_id";
	private static final String FIELD_NATION_ID="nation_id";
	
	private static final String TABLE_CREATE = "CREATE TABLE IF NOT EXISTS `"+
			TABLE_NAME+"`(`"+
			FIELD_ID+"` INTEGER PRIMARY KEY AUTOINCREMENT,`"+
			FIELD_ISLAND_NAME+"` TEXT NOT NULL,`"+
			FIELD_ISLAND_X+"` REAL NOT NULL,`"+
			FIELD_ISLAND_Y+"` REAL NOT NULL,`"+
			FIELD_PROFILE_ID+"` INTEGER NOT NULL REFERENCES profiles(_id),`"+
			FIELD_NATION_ID+"` INTEGER);";
	private static final String TABLE_DELETE = "DROP TABLE IF EXISTS `"+TABLE_NAME+"`;";
	private static final String PROFILE_DELETE_WHERE_CLAUSE = "`"+FIELD_PROFILE_ID+"`=?";

	public IslandTableProvider(IslandInterloperDatabase theParent) {
		super(theParent);
	}

	@Override
	public void onCreate(SQLiteDatabase theDatabase) {
		theDatabase.execSQL(TABLE_CREATE);
	}

	@Override
	public void onUpgrade(SQLiteDatabase theDatabase, int theOldVersion,
			int theNewVersion) {
		theDatabase.execSQL(TABLE_DELETE);
		onCreate(theDatabase);
	}

	public void createIslandsForProfile(Profile theProfile,
			List<WorldPosition> theIslandPositions,
			List<String> theIslandNames, Random theRandom) {
		getParent().getWritableDatabase().delete(TABLE_NAME, PROFILE_DELETE_WHERE_CLAUSE, new String[]{theProfile.getId().toString()});
		//TODO do a check for matching names and positions
		Iterator<WorldPosition> positionIterator = theIslandPositions.iterator();
		Iterator<String> nameIterator = theIslandNames.iterator();
		while(positionIterator.hasNext()){
			WorldPosition thePosition = positionIterator.next();
			String theName = nameIterator.next();
			ContentValues values = new ContentValues();
			values.put(FIELD_ISLAND_NAME, theName);
			values.put(FIELD_ISLAND_X, thePosition.getX());
			values.put(FIELD_ISLAND_Y, thePosition.getY());
			values.put(FIELD_PROFILE_ID, theProfile.getId());
			values.put(FIELD_NATION_ID, (Long)null);
			getParent().getWritableDatabase().insert(TABLE_NAME, null, values);
		}
	}

}
